package com.kingdee.pda.ui.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.device.ScanManager;
import android.device.scanner.configuration.PropertyID;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.basecommon.utils.SpeakUtils;
import com.kingdee.pda.R;
import com.kingdee.pda.entity.Warehouse;
import com.kingdee.pda.util.WarehouseUtil;
import com.kingdee.pda.plugins.http.common.OnRequestCallback;
import com.kingdee.pda.plugins.http.serverinterface.IWarehouse;
import com.kingdee.pda.plugins.http.serverinterface.impl.WarehouseImpl;
import com.kingdee.pda.callback.OnConfirmClickCallback;
import com.kingdee.pda.ui.popupwindow.WarehouseFilterPpWindow;
import com.kingdee.pda.util.ScreenUtils;
import com.kingdee.pda.util.ToastUtils;

import java.util.List;

/**
 * 基础标题页面父类
 * Created by zhanlg
 * DATE 2021/5/24
 * TIME 17:44
 * 继承当前类的子类，布局必须添加 layout_base_title
 */
public abstract class BaseTitleActivity extends BaseActivity implements View.OnClickListener {

    private ImageView mIvBack;
    private TextView mTvTitle;
    private TextView mTvWarehouseName;
    /**
     * 当前仓库
     **/
    private Warehouse mCurrentWarehouse;
    private IWarehouse mIWarehouse;
    private ScanManager mScanManager;


    /**
     * 更换仓库
     *
     * @param warehouse
     */
    public abstract void changeWarehouse(Warehouse warehouse);

    public void getScanResult(String scanResult) {
        if (TextUtils.isEmpty(scanResult)) {
            SpeakUtils.speakWithToast(this, "扫码结果为空，请重试", false, false);
            return;
        }
        if (getCurrentWarehouse() == null) {
            SpeakUtils.speakWithToast(this, "当前仓库信息获取失败", false, false);
            return;
        }

        try {
            if (focusEditText != null) {
                focusEditText.setText(scanResult);
                focusEditText.selectAll();
//                focusEditText.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    @Override
    protected void onActivityCreate(Bundle savedInstanceState) {

    }

    @Override
    protected void initView() {
        mIvBack = findViewById(R.id.iv_back);
        mTvTitle = findViewById(R.id.tv_title);
        mTvWarehouseName = findViewById(R.id.tv_warehouse_name);
        mIvBack.setOnClickListener(this);
        mTvTitle.setOnClickListener(this);
        mTvWarehouseName.setOnClickListener(this);
        findViewById(R.id.iv_setting).setOnClickListener(this);
    }

    /**
     * 设置返回键不显示
     */
    public void setBackViewGone() {
        mIvBack.setVisibility(View.GONE);
    }

    /**
     * 设置标题
     *
     * @param title
     */
    public void setTitle(String title) {
        mTvTitle.setText(title);
    }

    /**
     * 获取当前仓库信息
     *
     * @return
     */
    public Warehouse getCurrentWarehouse() {
        return mCurrentWarehouse;
    }

    @Override
    protected void initData() {
        mIWarehouse = new WarehouseImpl();
        mCurrentWarehouse = WarehouseUtil.getCurrentWarehouse();
        if (mCurrentWarehouse != null) {
            mTvWarehouseName.setText(mCurrentWarehouse.getName());
        } else {
            queryCurrentWarehouse();
        }

        initScanManager();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
            case R.id.tv_title:
                if (mIvBack.getVisibility() == View.VISIBLE) {
                    finish();
                }
                break;
            case R.id.tv_warehouse_name:
            case R.id.iv_setting:
                SettingActivity.actionStart(this);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == SettingActivity.REQUEST_CODE) {
            toShowWarehouseSelector();
        }
    }

    private void toShowWarehouseSelector() {
        List<Warehouse> warehouseList = WarehouseUtil.getWarehouseList();
        if (warehouseList != null && warehouseList.size() > 0) {
            showWarehousePpWindow(warehouseList);
        } else {
            queryWarehouseList();
        }
    }

    private void showWarehousePpWindow(List<Warehouse> warehouseList) {
        WarehouseFilterPpWindow warehouseSelector = new WarehouseFilterPpWindow(this,
                ScreenUtils.getScreenWidth(this),
                warehouseList,
                new OnConfirmClickCallback<Warehouse>() {
                    @Override
                    public void onConfirmClick(Warehouse warehouse) {
                        mTvWarehouseName.setText(warehouse.getName());
                        WarehouseUtil.saveCurrentWarehouse(warehouse);
                        saveSelectedWarehouse(warehouse);
                    }

                    @Override
                    public void onCancel() {

                    }
                });
        warehouseSelector.setFocusable(true);
        warehouseSelector.showAsDropDown(mTvWarehouseName, 0, 0);
    }

    private void queryWarehouseList() {
        showLoadingDialog();
        mIWarehouse.queryWarehouseList(this, true, new OnRequestCallback<List<Warehouse>>() {
            @Override
            public void onFailedCallback(boolean isRequestCallback, final String errorMsg) {
                super.onFailedCallback(isRequestCallback, errorMsg);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissLoadingDialog();
                        ToastUtils.showLong(BaseTitleActivity.this, errorMsg);
                    }
                });
            }

            @Override
            public void onSuccessCallback(final List<Warehouse> result, Object object) {
                super.onSuccessCallback(result, object);
                WarehouseUtil.saveWarehouseList(result);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissLoadingDialog();
                        showWarehousePpWindow(result);
                    }
                });
            }
        });
    }

    private void saveSelectedWarehouse(final Warehouse selectedWarehouse) {
        showLoadingDialog();
        mIWarehouse.saveWarehouse(selectedWarehouse.getId(), new OnRequestCallback<Warehouse>() {
            @Override
            public void onFailedCallback(boolean isRequestCallback, final String errorMsg) {
                super.onFailedCallback(isRequestCallback, errorMsg);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissLoadingDialog();
                        ToastUtils.showLong(BaseTitleActivity.this, errorMsg);
                    }
                });
            }

            @Override
            public void onSuccessCallback(Warehouse result, Object object) {
                super.onSuccessCallback(result, object);
                mCurrentWarehouse = selectedWarehouse;
                WarehouseUtil.saveCurrentWarehouse(mCurrentWarehouse);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissLoadingDialog();
                        ToastUtils.showShort(BaseTitleActivity.this, "仓库更换成功！");
                        changeWarehouse(mCurrentWarehouse);
                    }
                });
            }
        });
    }

    private void queryCurrentWarehouse() {
        mIWarehouse.queryCurrentWarehouse(new OnRequestCallback<Warehouse>() {
            @Override
            public void onFailedCallback(boolean isRequestCallback, String errorMsg) {
                super.onFailedCallback(isRequestCallback, errorMsg);
            }

            @Override
            public void onSuccessCallback(final Warehouse result, Object object) {
                super.onSuccessCallback(result, object);
                mCurrentWarehouse = result;
                WarehouseUtil.saveCurrentWarehouse(mCurrentWarehouse);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mTvWarehouseName.setText(mCurrentWarehouse.getName());
                    }
                });
            }
        });
    }

    public void updateWarehouseName() {
        Warehouse warehouse = WarehouseUtil.getCurrentWarehouse();
        if (warehouse != null) {
            this.mCurrentWarehouse = warehouse;
            mTvWarehouseName.setText(mCurrentWarehouse.getName());
        }
    }

    @Override
    protected void onNetworkAvailable() {

    }

    @Override
    protected void onNetworkError() {
        ToastUtils.showLong(this, "网络连接失败");
    }


    /**
     * 初始化设备扫码器
     */
    public void initScanManager() {
        if (mScanManager == null)
            mScanManager = new ScanManager();
    }

    /**
     * 扫码结果广播接收器
     */
    private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ScanManager.ACTION_DECODE.equals(action)) {
                // Get scan results, including string and byte data etc.
                byte[] barcode = intent.getByteArrayExtra(ScanManager.DECODE_DATA_TAG);
                int barcodeLen = intent.getIntExtra(ScanManager.BARCODE_LENGTH_TAG, 0);
                String scanResult = new String(barcode, 0, barcodeLen);
//                ToastUtils.showLong(BaseTitleActivity.this, scanResult);
                getScanResult(scanResult);
            }
        }
    };

    public void registerScanReceiver() {
        if (mScanManager != null) {
            try {
                IntentFilter filter = new IntentFilter();
                int[] idbuf = new int[]{PropertyID.WEDGE_INTENT_ACTION_NAME, PropertyID.WEDGE_INTENT_DATA_STRING_TAG};
                String[] value_buf = mScanManager.getParameterString(idbuf);
                if (value_buf != null && value_buf[0] != null && !value_buf[0].equals("")) {
                    filter.addAction(value_buf[0]);
                } else {
                    filter.addAction(ScanManager.ACTION_DECODE);
                }
                registerReceiver(mScanReceiver, filter);
            } catch (RuntimeException e) {
                e.printStackTrace();
            }
        }
    }

    public void unregisterScanReceiver() {
        if (mScanManager != null) {
            try {
                mScanManager.stopDecode();
                unregisterReceiver(mScanReceiver);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mCurrentWarehouse != null) {
            mCurrentWarehouse = null;
        }
        if (mScanManager != null) {
            mScanManager = null;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerScanReceiver();
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterScanReceiver();
    }
}
